<template>
  <view class="modal page-modal" :class="show ? 'show' : 'hide'">
    <PageLayout full :page-style="mergedPageStyle" :footer-size="footerSize">
      <template #header>
        <HeaderLayout prevent-back :show-back="showBack" :back-text="goBackText" @back="goBack">
          <text v-if="title" class="title">{{ title }}</text>
          <slot name="header"></slot>
        </HeaderLayout>
      </template>

      <view class="modal-body" :style="bodyStyle">
        <slot></slot>
      </view>

      <template #footer>
        <FooterLayout :size="footerSize" :footer-style="footerStyle">
          <slot name="footer"></slot>
        </FooterLayout>
      </template>
    </PageLayout>
  </view>
</template>

<script setup lang="ts">
import type { CSSProperties } from 'vue'
import PageLayout from '@/layout/page/page.vue'
import HeaderLayout from '@/layout/page/header.vue'
import FooterLayout from '@/layout/page/footer.vue'
import { useI18n } from 'vue-i18n'
import { useDismissInject } from '@/layout/page/constants'

const props = withDefaults(
  defineProps<{
    show: boolean
    title?: string
    showBack?: boolean // 显示返回按钮
    backText?: string // 返回按钮文本
    preventBack?: boolean
    pageStyle?: CSSProperties
    bodyStyle?: CSSProperties
    footerStyle?: CSSProperties
    footerSize?: string
  }>(),
  {
    showBack: true,
  }
)
const emit = defineEmits<{
  (e: 'update:show', show: boolean): void
  (e: 'close'): void
  (e: 'back'): void
}>()

const i18n = useI18n()
const goBackText = computed(() => (props.showBack ? i18n.t(props.backText || '') : ''))

const mergedPageStyle = computed<CSSProperties>(() => ({
  backgroundColor: '#ffffff',
  ...props.pageStyle,
}))
function closeModal() {
  emit('update:show', false)
  emit('close')
}

/**
 * 返回处理
 */
function goBack() {
  emit('back')

  if (props.preventBack) return

  closeModal()
}
useDismissInject(() => props.show, goBack)
</script>

<style scoped lang="less">
@import '@/styles/modal.less';
.page-modal {
  height: 100%;
}
.modal-body {
  height: 100%;
  box-sizing: border-box;
}
</style>
